/**
 * 
 */
package com.fnic.pearl.scheduler.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.fnic.pearl.scheduler.constant.PearlErrorCode;
import com.fnic.pearl.scheduler.constant.TaskType;
import com.fnic.pearl.scheduler.constant.TestTaskStatus;
import com.fnic.pearl.scheduler.dao.SchedulerStore;
import com.fnic.pearl.scheduler.model.TaskError;
import com.fnic.pearl.scheduler.model.TaskStats;
import com.fnic.pearl.scheduler.model.TestTask;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;


/**
 * 接收 下发测量任务
 * 
 * @author HuHaiyang
 * @date 2013年7月29日
 */
public class TestTaskIssueServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static Logger LOG = Logger.getLogger(TestTaskIssueServlet.class);
    private Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        List<TestTask> tts = null;
        try
        {
            tts = gson.fromJson(req.getReader(), 
                    new TypeToken<List<TestTask>>(){}.getType());
        }
        catch (JsonSyntaxException jse)
        {
            LOG.warn("doPost - invalid json!");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        if (tts.size() == 0)
        {
            LOG.warn("TestTaskIssue - no task!");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return ;
        }
        
        List<TaskError> errors = new ArrayList<TaskError>();
        for (TestTask tt : tts)
        {
            if (tt == null)
            {
                LOG.warn("invalid testask, is null!");
                continue;
            }
            else if (tt.getTaskId() <= 0)
            {
                LOG.warn("invalid testask, taskId [" + tt.getTaskId() + "] <= 0");
                errors.add(new TaskError(tt.getTaskId(), PearlErrorCode.SCHD_ERR_SVC_TASK_ID_INVALID));
                continue;
            }
            else if (!(tt.getProbe() != null && tt.getProbe() > 0))
            {
                LOG.warn("invalid testask, Probe or serial is null or less than 0");
                errors.add(new TaskError(tt.getTaskId(), PearlErrorCode.SCHD_ERR_SVC_PROBE_ID_INVALID));
                continue;
            }
            else if (tt.getToolName() == null || tt.getToolName().length() <= 0)
            {
                LOG.warn("invalid testask, Tool is null or less than 0");
                errors.add(new TaskError(tt.getTaskId(), PearlErrorCode.SCHD_ERR_SVC_TOOL_INVALID));
                continue;
            }
            else if (tt.getRun() != TestTask.RUN_IMMEDIATE
                    && tt.getRun() != TestTask.RUN_TIMING)
            {
                LOG.warn("invalid testask Run [" + tt.getRun() + "]");
                errors.add(new TaskError(tt.getTaskId(), PearlErrorCode.SCHD_ERR_SVC_RUN_INVALID));
                continue;
            }
            else if (tt.getEndTime() != null)
            {
                final Calendar now = Calendar.getInstance();
                Calendar endCal = Calendar.getInstance();
                endCal.setTime(tt.getEndTime());
                if (now.compareTo(endCal) >= 0)
                {
                    LOG.info("scheduler rule - now >= end");
                    errors.add(new TaskError(tt.getTaskId(), PearlErrorCode.SCHD_ERR_SVC_INVALID_END_TIME));
                    continue;
                }
            }
            
            tt.setTaskType(TaskType.TEST_TASK);
            LOG.info("recv testask - " + tt);
            tt.setStatus(TestTaskStatus.S_NEW_TASK);
            TaskStats.getInstance().incrRecvTaskNum();
            SchedulerStore.getInstance().putInitTestTask(tt);
        }
        
        if (errors.size() == 0)
        {
            resp.setStatus(HttpServletResponse.SC_OK);
            return ;
        }
        
        resp.setContentType("application/json;charset=utf-8");
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        resp.getWriter().write(gson.toJson(errors));
        resp.getWriter().flush();
    }
}
